package member

import (
    "fmt"
    "dhfshop/service/redisgo"
	"dhfshop/models/member"
	"dhfshop/models/org"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
)

type SubscribeController struct {
	base.BaseController
}

func (this *SubscribeController) SqlGet() {
	//partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	appId := "wx204da65aa7d948b0"
	user, err := org.GetUserByUserId(curUserId)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
	members, err := member.GetMemberIdByUnionid(appId, user.Unionid)
	if err != nil {
		this.ServeError(err.Error())
	    return   
	}
	rsp := struct {
		IsSubscribe  bool  `json:"is_subscribe"`
	}{IsSubscribe: members.IsSubScribe}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *SubscribeController) CacheGet() {
	var isSubscribe bool = false
	v := struct {
		SceneId  string  `form:"scene_id" valid:"Required"`
	}{} 
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	//partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	user, err := org.GetUserByUserId(curUserId)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
	redisconn := redisgo.GetInstance()
	cacheKey := fmt.Sprintf("%s%d", user.Unionid, 1100)
	if cacheValue, err := redisconn.GetString(cacheKey); err == nil && len(cacheValue) > 5  {
		if cacheValue == v.SceneId {
		   isSubscribe = true
		}
	}
	rsp := struct {
		IsSubscribe  bool  `json:"is_subscribe"`
	}{IsSubscribe: isSubscribe}
	this.Data["json"] = rsp
	this.ServeJSON()
}
